/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.controller;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.net.URLEncoder;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.sesame.domain.User;
import com.sesame.service.UserService;
import com.sesame.toolkit.Encrypt;

/**
 * @author r6c
 * 
 */
public class UploadHeadPicController extends SimpleFormController {

    private UserService userService;
    private String imageBase;
    private Integer userId = null;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setImageBase(String imageBase) {
        this.imageBase = imageBase;
    }

    protected Object formBackingObject(HttpServletRequest request)
            throws Exception {
        userId = (Integer) request.getSession().getAttribute("userId");
        User user = userService.showUser(userId);
        return user;
    }

    protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {
        MultipartFile srcFile = null;
        File outFile = null;
        String srcFileName = null;
        String outFileName = null;
        BufferedImage bufferedImage = null;
        BufferedImage outImage = null;
        Image image = null;
        User user = (User) command;
        user.setId(userId);
        Map model = errors.getModel();
        int width;
        int height;

        if (!(request instanceof MultipartHttpServletRequest)) {
            model.put("error_uploadHeadPic", "无上传文件！");
            return new ModelAndView(getFormView(), model);
        }

        MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
        srcFile = multipart.getFile("userPic");
        if (srcFile == null || srcFile.isEmpty()) {
            model.put("error_uploadHeadPic", "无上传文件！");
            return new ModelAndView(getFormView(), model);
        }

        outFileName = "00000/" + userId + "_" + System.currentTimeMillis();
        try {
            bufferedImage = ImageIO.read(srcFile.getInputStream());
            if (bufferedImage == null) {
                model.put("error_uploadHeadPic", "图片格式不正确！");
                return new ModelAndView(getFormView(), model);
            }
            width = bufferedImage.getWidth();
            height = bufferedImage.getHeight();
            image = bufferedImage.getScaledInstance(120, 120,
                    Image.SCALE_DEFAULT);
            outImage = new BufferedImage(120, 120, Image.SCALE_DEFAULT);
            outImage.getGraphics().drawImage(image, 0, 0, null);

            outFile = new File(imageBase + outFileName + ".jpg");
            ImageIO.write(outImage, "jpeg", outFile);
            user.setHeadPic(Encrypt.MapEncrypt(outFileName));
            boolean isModifyHeadPic = userService.modifyHeadPic(user, model);

            if (!isModifyHeadPic) {
                model.put("error_uploadHeadPic", "修改失败，请重试！");
                return new ModelAndView(getFormView(), model);
            }
        } catch (IOException ioe) {
        }
        request.getSession().setAttribute("headPic", user.getHeadPic());
        return new ModelAndView(getSuccessView(), model);
    }
}